import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class MathProblemGUI extends JFrame {
    private List<MathProblem> problems;
    private int currentIndex;

    private JLabel problemLabel;
    private JLabel answerLabel;
    private JLabel countLabel;
    private JButton prevButton;
    private JButton nextButton;
    private JButton showAnswerButton;
    private JPanel answerPanel;

    public MathProblemGUI() {
        problems = new ArrayList<>();
        currentIndex = 0;

        initializeGUI();
        loadProblemsFromCSV("math_problems.csv");
        updateDisplay();
    }

    private void initializeGUI() {
        setTitle("口算习题练习系统");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 350);
        setLocationRelativeTo(null);

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 标题面板
        JLabel titleLabel = new JLabel("100以内加减法口算练习", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        titleLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));

        // 问题显示区域
        JPanel problemPanel = new JPanel(new BorderLayout());
        problemPanel.setBorder(BorderFactory.createTitledBorder("当前习题"));

        problemLabel = new JLabel("", JLabel.CENTER);
        problemLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        problemLabel.setForeground(Color.BLUE);
        problemPanel.add(problemLabel, BorderLayout.CENTER);

        // 答案面板（初始隐藏）
        answerPanel = new JPanel(new BorderLayout());
        answerPanel.setBorder(BorderFactory.createTitledBorder("答案"));
        answerLabel = new JLabel("", JLabel.CENTER);
        answerLabel.setFont(new Font("微软雅黑", Font.PLAIN, 20));
        answerLabel.setForeground(Color.RED);
        answerPanel.add(answerLabel, BorderLayout.CENTER);
        answerPanel.setVisible(false); // 初始隐藏答案

        // 计数标签
        countLabel = new JLabel("", JLabel.CENTER);
        countLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        countLabel.setForeground(Color.GRAY);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));

        prevButton = new JButton("上一题 (←)");
        nextButton = new JButton("下一题 (→)");
        showAnswerButton = new JButton("显示答案");

        // 设置按钮字体和大小
        Font buttonFont = new Font("微软雅黑", Font.PLAIN, 14);
        prevButton.setFont(buttonFont);
        nextButton.setFont(buttonFont);
        showAnswerButton.setFont(buttonFont);

        // 设置按钮大小
        Dimension buttonSize = new Dimension(120, 35);
        prevButton.setPreferredSize(buttonSize);
        nextButton.setPreferredSize(buttonSize);
        showAnswerButton.setPreferredSize(buttonSize);

        // 添加按钮监听器
        prevButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showPreviousProblem();
            }
        });

        nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showNextProblem();
            }
        });

        showAnswerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                toggleAnswer();
            }
        });

        // 添加键盘快捷键
        setupKeyboardShortcuts();

        buttonPanel.add(prevButton);
        buttonPanel.add(showAnswerButton);
        buttonPanel.add(nextButton);

        // 组装主界面
        JPanel centerPanel = new JPanel(new BorderLayout(10, 10));
        centerPanel.add(problemPanel, BorderLayout.NORTH);
        centerPanel.add(answerPanel, BorderLayout.CENTER);
        centerPanel.add(countLabel, BorderLayout.SOUTH);

        mainPanel.add(titleLabel, BorderLayout.NORTH);
        mainPanel.add(centerPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(mainPanel);
    }

    private void setupKeyboardShortcuts() {
        // 添加快捷键支持
        InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actionMap = getRootPane().getActionMap();

        // 左箭头 - 上一题
        inputMap.put(KeyStroke.getKeyStroke("LEFT"), "prevProblem");
        actionMap.put("prevProblem", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showPreviousProblem();
            }
        });

        // 右箭头 - 下一题
        inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "nextProblem");
        actionMap.put("nextProblem", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showNextProblem();
            }
        });

        // 空格键 - 显示/隐藏答案
        inputMap.put(KeyStroke.getKeyStroke("SPACE"), "toggleAnswer");
        actionMap.put("toggleAnswer", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                toggleAnswer();
            }
        });
    }

    private void loadProblemsFromCSV(String filename) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            boolean isFirstLine = true;
            int loadedCount = 0;

            while ((line = reader.readLine()) != null) {
                if (isFirstLine) {
                    isFirstLine = false;
                    continue; // 跳过标题行
                }

                String[] parts = line.split(",");
                if (parts.length >= 2) {
                    String problem = parts[0].trim();
                    int answer = Integer.parseInt(parts[1].trim());
                    problems.add(new MathProblem(problem, answer));
                    loadedCount++;
                }
            }

            System.out.println("成功从CSV文件加载 " + loadedCount + " 道习题");

            if (loadedCount == 0) {
                JOptionPane.showMessageDialog(this,
                        "CSV文件中没有找到习题数据，请先运行MathProblemGenerator生成习题",
                        "提示",
                        JOptionPane.INFORMATION_MESSAGE);
            }

        } catch (IOException e) {
            JOptionPane.showMessageDialog(this,
                    "读取CSV文件失败: " + e.getMessage() + "\n请先运行MathProblemGenerator生成习题文件",
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this,
                    "CSV文件格式错误",
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    private void showPreviousProblem() {
        if (currentIndex > 0) {
            currentIndex--;
            updateDisplay();
        } else {
            // 如果是第一题，可以循环到最后一道题
            // currentIndex = problems.size() - 1;
            // updateDisplay();
            Toolkit.getDefaultToolkit().beep(); // 提示音
        }
    }

    private void showNextProblem() {
        if (currentIndex < problems.size() - 1) {
            currentIndex++;
            updateDisplay();
        } else {
            // 如果是最后一题，可以循环到第一道题
            // currentIndex = 0;
            // updateDisplay();
            Toolkit.getDefaultToolkit().beep(); // 提示音
        }
    }

    private void toggleAnswer() {
        if (problems.isEmpty()) return;

        boolean isVisible = answerPanel.isVisible();
        answerPanel.setVisible(!isVisible);

        if (!isVisible) {
            MathProblem currentProblem = problems.get(currentIndex);
            answerLabel.setText(String.valueOf(currentProblem.getAnswer()));
            showAnswerButton.setText("隐藏答案");
        } else {
            showAnswerButton.setText("显示答案");
        }
    }

    private void updateDisplay() {
        // 隐藏答案当切换题目时
        answerPanel.setVisible(false);
        showAnswerButton.setText("显示答案");

        if (problems.isEmpty()) {
            problemLabel.setText("没有可用的习题");
            countLabel.setText("请先运行MathProblemGenerator生成习题文件");
            prevButton.setEnabled(false);
            nextButton.setEnabled(false);
            showAnswerButton.setEnabled(false);
            return;
        }

        MathProblem currentProblem = problems.get(currentIndex);
        problemLabel.setText(currentProblem.getProblem());
        countLabel.setText("第 " + (currentIndex + 1) + " 题 / 共 " + problems.size() + " 题");

        // 更新按钮状态
        prevButton.setEnabled(currentIndex > 0);
        nextButton.setEnabled(currentIndex < problems.size() - 1);
        showAnswerButton.setEnabled(true);

        // 更新按钮文本提示
        if (currentIndex == 0) {
            prevButton.setText("上一题 (第一题)");
        } else {
            prevButton.setText("上一题 (←)");
        }

        if (currentIndex == problems.size() - 1) {
            nextButton.setText("下一题 (最后一题)");
        } else {
            nextButton.setText("下一题 (→)");
        }
    }

    public static void main(String[] args) {
        // 设置GUI外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MathProblemGUI().setVisible(true);
            }
        });
    }
}